package com.qj.daibei.controller;

import com.github.pagehelper.PageInfo;
import com.qj.daibei.pojo.Overdue;
import com.qj.daibei.pojo.ShouldPayBack;
import com.qj.daibei.pojo.ShouldPayBackCustom;
import com.qj.daibei.pojo.User;
import com.qj.daibei.service.LoanService;
import com.qj.daibei.service.OverdueService;
import com.qj.daibei.service.ShouldPayBackService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * author wml
 * Created on 2021/10/22 21:54
 */
@Controller
public class ShouldPayBackController {

    @Autowired
    private ShouldPayBackService shouldPayBackService;

    @Autowired
    private LoanService loanService;

    @Autowired
    private OverdueService overdueService;

    @RequestMapping("/findShouldPayBackCustomByLoanIdByPage")
    @ResponseBody
    public PageInfo<ShouldPayBackCustom> findShouldPayBackCustomByLoanIdByPage(HttpSession session, int pageNum, int pageSize) {
//        System.out.println(pageNum + "," + pageSize);
        User user = (User) session.getAttribute("loginUser");
        List<Object> loanIdList = this.loanService.findLoanIdByUserId(user.getUserId());

        List<ShouldPayBackCustom> shouldPayBackCustomList = this.shouldPayBackService.findShouldPayBackCustomByLoanIdAndOverdue(loanIdList);
        if (shouldPayBackCustomList.size() != 0) {
            // 把逾期记录插入到逾期表
            List<Overdue> overdueList = new ArrayList<>();
            for (ShouldPayBackCustom shouldPayBackCustom: shouldPayBackCustomList) {
                Overdue overdue = new Overdue();
                overdue.setOMoney(100f);
                overdue.setOStatus("未还款");
                overdue.setSpbId(shouldPayBackCustom.getSpbId());
                overdue.setUserId(user.getUserId());

                ShouldPayBack shouldPayBack = new ShouldPayBack();
                shouldPayBack.setSpbId(shouldPayBackCustom.getSpbId());
                shouldPayBack.setSpbStatus("已逾期");
                this.shouldPayBackService.updateShouldPayBackById(shouldPayBack);

                overdueList.add(overdue);
            }
//            System.out.println(overdueList);
            this.overdueService.insertOverdueByBatch(overdueList);

        }

        PageInfo<ShouldPayBackCustom> pageInfo = this.shouldPayBackService.findShouldPayBackCustomByLoanIdByPage(loanIdList, pageNum, pageSize);
        return pageInfo;
    }
}
